<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(0);

class Login extends CI_Controller {

	function __construct() {
		parent::__construct();
		

	}
	public function validaActiveDirectory($user, $password,$group){
	
		// Active Directory server
		$ldap_host = "tucano.arapongas.pr.gov.br";
		// Active Directory DN
		$ldap_dn = "OU=Usuarios,DC=arapongas,DC=pr,DC=gov,DC=br";
		// Domain, for purposes of constructing $user
		$ldap_usr_dom = "@arapongas.pr.gov.br";
		
		// Connect to AD
		$ldap = ldap_connect($ldap_host) or die('<div class="alert alert-danger" role="alert">Erro ao conectar no servidor</div>');
		
		if($ldap) {
			$ldapbind = ldap_bind($ldap,$user.$ldap_usr_dom,$password) or die('<div class="alert alert-danger" role="alert">Erro ao consultar servidor</div>');
			if($ldapbind) {
				$query = "(&(objectClass=user)(objectCategory=person)(memberof=CN=$group,OU=Grupos,DC=arapongas,DC=pr,DC=gov,DC=br))";
				$attr = array("sAMAccountName");
				$results = ldap_search($ldap,$ldap_dn,$query,$attr) or die ('<div class="alert alert-danger" role="alert">Erro na busca: '.ldap_error($ldap).'</div>');
				$entries = ldap_get_entries($ldap, $results);
				array_shift($entries);
				$data = array();
				foreach($entries as $user1){
					$string = $user1['samaccountname'][0];
					$data[] = $string;
				}
				if(in_array($user, $data)){
					return true;
				}else{
					return false;
				}
			}else{
				return false;
			}
		}else{
			echo '<div class="alert alert-danger" role="alert">Nenhum servidor encontrado</div>';
		}
	
	
	}
	
	public function index(){
		if($this->input->post()){
		
			$log = new Log();
			$usuario = new Usuario();
			$usuario->where("login",$this->input->post('userLogin'))->where("status","1")->limit('1')->get();
			//echo $usuario->check_last_query();
			if($usuario->exists()){
				//if($this->validaActiveDirectory($this->input->post('userLogin'), $this->input->post('userPassword'),$usuario->grupoAD)){
					
					$newdata = array(
						'nome'  => $this->input->post('userLogin'),
						'permissao'  => $usuario->permissao_id,
						'usuario_id'  => $usuario->id,
						'logado' => TRUE
					);
					//$this->session->set_userdata($newdata);
					$this->session->set_userdata('grambel', $newdata);
					
					$usuario->dt_ultimo_acesso = date('Y-m-d H:i:s');
					$usuario->save();
					//echo $usuario->check_last_query();
					
					//LOG DE ACESSO
					$log->ip = $this->session->userdata('ip_address');
					$log->usuario = $usuario->login;
					$log->acao = 'SUCESSO LOGIN - USUÁRIO LOGOU';
					//$log->dt_log = date('Y-m-d H:i:s');
					$log->save();
					
			//*********************************************************************************************
					
					echo "success";
				/*}else{

					$this->session->set_userdata();
					
					//LOG DE ACESSO
					$log->ip = $this->session->userdata('ip_address');
					$log->usuario = $this->input->post('userLogin');
					$log->acao = 'ERRO LOGIN - USUÁRIO OU SENHA INCORRETOS';
					$log->dt_log = date('Y-m-d H:i:s');
					$log->save();
					$this->session->sess_destroy();
					echo '<div class="alert alert-danger" role="alert">Erro de login ou senha</div>';
				}
				*/
			}else{
				$this->session->set_userdata();
				
				//LOG DE ACESSO
				$log->ip = $this->session->userdata('ip_address');
				$log->usuario = $this->input->post('userLogin');
				$log->acao = 'ERRO LOGIN - USUÁRIO SEM PERMISSÃO';
				//$log->dt_log = date('Y-m-d H:i:s');
				$log->save();
				
				$this->session->sess_destroy();
				echo '<div class="alert alert-danger" role="alert">Vc não tem permissão de acesso</div>';
			}
		}else{
			$this->load->view('view_login');
		}
		
		
	}

	public function sair(){
	
		$session_data = $this->session->userdata('grambel');
		
		//LOG DE ACESSO
		$log = new Log();
		
		$log->ip = $this->session->userdata('ip_address');
		$log->usuario = $session_data["nome"];
		$log->acao = "LOGOUT";
		//$log->dt_log = date('Y-m-d H:i:s');
		$log->save();
		
		$this->session->sess_destroy();
		$this->session->unset_userdata('grambel');
		redirect('inicio');
	
	
	}

	
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */